package jp.sourceforge.akjrcp.text_douga.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

import jp.sourceforge.akjrcp.text_douga.item.ColorItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.imageio.plugins.gif.GIFImageMetadata;
import com.sun.imageio.plugins.gif.GIFImageReader;

public class GifAnimeUtils {
	public static Log log=LogFactory.getLog(ColorItem.class);
	
	public static GIFImageReader getGifReader(File file){
		
		GIFImageReader reader = (GIFImageReader) ImageIO.getImageReadersByFormatName("GIF").next();
		if(reader==null){
			log.warn("gif reader not found");
			return null;
		}
		
		ImageInputStream iis;
		try {
			iis = ImageIO.createImageInputStream(new FileInputStream(file));
			 reader.setInput(iis);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   
	    
	    return reader;
	}
	
	public static int findAnimationFrame(GIFImageReader reader,double animationTime){
		double mod=animationTime%getGifDuration(reader);//for loop
		
		int delayed= new BigDecimal(""+mod).multiply(new BigDecimal(100)).intValue();
		//log.info("mod:"+mod+" fnumber:"+delayed);
		int num;
		try {
			num = reader.getNumImages(true);
			int total=0;
			for (int i = 0; i < num; i++) {
	         	GIFImageMetadata md = (GIFImageMetadata) reader.getImageMetadata(i);
				total+=Math.max(1,md.delayTime); //some gif anime has all 0 deley
				if(delayed<total){
					return i;
				}
				}
		} catch (IIOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.warn("invalid fnumber:"+delayed);
		return 0;
	}
	
	public static int countFrames(GIFImageReader reader){
		try {
			return reader.getNumImages(true);
		} catch (IIOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	public static double getGifDuration(GIFImageReader reader){
		double duration=0;
		 int num;
		try {
			num = reader.getNumImages(true); //true measn allow search
			//log.info("frame nums:"+num);
			int deleys=0;		// divided 100
			for (int i = 0; i < num; i++) {
	         	GIFImageMetadata md = (GIFImageMetadata) reader.getImageMetadata(i);
				deleys+=Math.max(1,md.delayTime);	//some gif anime has all 0 deley	
				//log.info(md.delayTime);
				}
			if(deleys>0){
				duration=new BigDecimal(""+deleys).divide(new BigDecimal(100)).doubleValue();
			}
		} catch (IIOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return duration;
	}
}
